package com.zhongshengnetwork.rightbe;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhongshengnetwork.rightbe.Adv.activity.SplashActivity;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.Constant.LetterConstant;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.RCCommandUtils;
import com.zhongshengnetwork.rightbe.gsonmodel.LifeResultModel;

import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by luojingxing on 2018/11/3.
 */

public class MyJPUSHReceiver extends BroadcastReceiver {
    private static final String TAG = "MyJPUSHReceiver";

    private NotificationManager nm;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (null == nm) {
            nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }

        Bundle bundle = intent.getExtras();
        //Log.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + AndroidUtil.printBundle(bundle));
        Log.e(TAG, "onReceive - " + intent.getAction());

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            Log.e(TAG, "JPush 用户注册成功");
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.e(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.JPUSHRegistrationId,regId);
            MainActivity.uploadJPUSH(1);
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.e(TAG, "接受到推送下来的自定义消息");

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.e(TAG, "接受到推送下来的通知");

            receivingNotification(context,bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.e(TAG, "用户点击打开了通知");

            openNotification(context,bundle);

        }else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())){
            String regId = CommonUtils.formatString(SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.JPUSHRegistrationId,""));
            Log.e(TAG, "连接上的Registration Id : " + regId);
            MainActivity.uploadJPUSH(1);
        } else {
            Log.e(TAG, "Unhandled intent - " + intent.getAction());
        }
    }

    private void receivingNotification(Context context, Bundle bundle){
        String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
        Log.e(TAG, " title : " + title);
        String message = bundle.getString(JPushInterface.EXTRA_ALERT);
        Log.e(TAG, "message : " + message);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        Log.e(TAG, "extras : " + extras);
        if (!CommonUtils.isEmpty(extras)){
            try{
                String dataString = extras;
                Map<String, String> map = CommonUtils.json2map(dataString);
                if (map == null){
                    Log.e(TAG, "json为空");
                    return;
                }
                Log.e(TAG, "name="+map.get("name"));

                String msgname = map.get("msgType");
                String time = map.get("time");
                if (CommonUtils.isEmpty(msgname) || CommonUtils.isEmpty(time)){
                    Log.e(TAG, "json数据为空");
                    return;
                }

                if (msgname.equals(Constant.MessageType.Life_Result)) {//生活圈审核结果
                    RCCommandUtils.dealWithLifeResult(dataString,CustomApplication.mContext, Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.LifeLike_Result)) {//生活圈关注
                    RCCommandUtils.dealWithCare(dataString,CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.LifeDZ_Result)) {//生活圈笔芯信息
                    RCCommandUtils.dealWithLife(dataString,Integer.valueOf(Constant.MessageType.LifeDZ_Result),CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.LifeC_Result)) {//生活圈评论信息
                    RCCommandUtils.dealWithLife(dataString,Integer.valueOf(Constant.MessageType.LifeC_Result),CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.LifeCR_Result)) {//生活圈评论回复
                    RCCommandUtils.dealWithLife(dataString,Integer.valueOf(Constant.MessageType.LifeCR_Result),CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.LifeCL_Result)) {//生活圈评论笔芯
                    RCCommandUtils.dealWithLife(dataString,Integer.valueOf(Constant.MessageType.LifeCL_Result),CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.LangPrize_Result)) {//生活圈获奖
                    RCCommandUtils.dealWithLife(dataString,Integer.valueOf(Constant.MessageType.LangPrize_Result),CustomApplication.mContext,Long.valueOf(time));
                }else if(msgname.equals(Constant.MessageType.SelfInfo)){//系统通知
                    RCCommandUtils.dealWithSystem(dataString,Integer.valueOf(Constant.MessageType.SelfInfo),CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.Contact_Result)){//用户反馈
                    RCCommandUtils.dealWithSystem(dataString,Integer.valueOf(Constant.MessageType.Contact_Result),CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.Care_Lang_Update)){//关注用户发布了新的微句
                    Log.e("TAG","关注用户发布了新的微句");
                    SPManageUtils.getInstance(CustomApplication.mContext).putSPString(AdvertUtils.CareUpdateKey,"1");
                    Intent mIntent = new Intent(BroadcastDefine.CareLang_Update_Action);
                    //发送广播
                    CustomApplication.mContext.sendBroadcast(mIntent);
                }else if (msgname.equals(Constant.MessageType.New_Msg_Notify)){//有新的未读消息
                    if (CommonUtils.isLogin() == true){
                        SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.NewMsgNotifyKey+CustomApplication.loginModel.getUid(), true);
                    }
                }else if (msgname.equals(Constant.MessageType.New_SX_Notify)){
                    if (CommonUtils.isLogin() == true){
                        SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(LetterConstant.UnReadOfSXMSGKey, true);
                    }
                }else if (msgname.equals(Constant.MessageType.WeiShu_Like_Notify)) {//微纸条点赞通知
                    RCCommandUtils.dealWithWZT(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.WeiShu_Comment_Notify)) {//微纸条评论通知
                    RCCommandUtils.dealWithWZT(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.WeiShu_Subscribe_Notify)) {//微纸条订阅通知
                    RCCommandUtils.dealWithWZT(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.WeiShu_Content_Notify)) {//微纸条内容点赞、分享、评论、收藏通知
                    RCCommandUtils.dealWithWZT(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.WeiShu_Content_Comment_Notify)) {//微纸条评论点赞、回复、收藏通知
                    RCCommandUtils.dealWithWZT(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
                }else if (msgname.equals(Constant.MessageType.Classify_Request_Notify) || msgname.equals(Constant.MessageType.Classify_Authed_Notify)){
                    RCCommandUtils.dealWithClassify(dataString,Integer.valueOf(msgname),CustomApplication.mContext,Long.valueOf(time));
                }

            }catch (Exception e){
                Log.e(TAG, e.getMessage());
            }

        }
    }

    private void openNotification(Context context, Bundle bundle){
        /*
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        String myValue = "";
        try {
            JSONObject extrasJson = new JSONObject(extras);
            myValue = extrasJson.optString("myKey");
        } catch (Exception e) {
            Log.w(TAG, "Unexpected: extras is not a valid json", e);
            return;
        }
        if (TYPE_THIS.equals(myValue)) {
            Intent mIntent = new Intent(context, ThisActivity.class);
            mIntent.putExtras(bundle);
            mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mIntent);
        } else if (TYPE_ANOTHER.equals(myValue)){
            Intent mIntent = new Intent(context, AnotherActivity.class);
            mIntent.putExtras(bundle);
            mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(mIntent);
        }
        */
        String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
        Log.e(TAG, " title : " + title);
        String message = bundle.getString(JPushInterface.EXTRA_ALERT);
        Log.e(TAG, "message : " + message);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        Log.e(TAG, "extras : " + extras);

        //通知跟进内容类型做特殊处理，运营部分通知
        if (CommonUtils.isAppAlive(context,"com.zhongshengnetwork.rightbe")){
            Log.e("TAG","点击通知，还活着");
            Intent mainIntent = new Intent(context, SplashActivity.class);
            mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (!CommonUtils.isEmpty(extras)){
                LifeResultModel lifeResultModel = GsonTools.getLifeResultModel(extras);
                if (lifeResultModel != null){
                    Bundle b=new Bundle();
                    b.putSerializable("push", lifeResultModel);//序列化
                    mainIntent.putExtras(b);//发送数据
                }
            }
            context.startActivity(mainIntent);
        }else {
            Log.e("TAG","从通知栏重新打开应用");
            Intent launchIntent = context.getPackageManager().
                    getLaunchIntentForPackage("com.zhongshengnetwork.rightbe");
            launchIntent.setFlags(
                    Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            if (!CommonUtils.isEmpty(extras)){
                LifeResultModel lifeResultModel = GsonTools.getLifeResultModel(extras);
                if (lifeResultModel != null){
                    Bundle b=new Bundle();
                    b.putSerializable("push", lifeResultModel);//序列化
                    launchIntent.putExtras(b);//发送数据
                }
            }
            context.startActivity(launchIntent);
        }

    }
}
